<?php
header('Content-Type: application/json');

$dataFile = '../../data/heroes.json';

try {
    // 检查目录是否存在和可写
    $dir = dirname($dataFile);
    if (!is_dir($dir)) {
        throw new Exception('数据目录不存在');
    }
    if (!is_writable($dir)) {
        throw new Exception('数据目录不可写');
    }

    // 检查文件是否可写
    if (file_exists($dataFile) && !is_writable($dataFile)) {
        throw new Exception('数据文件不可写');
    }

    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['name']) || !isset($input['image']) || !isset($input['description'])) {
        throw new Exception('缺少必要参数');
    }
    
    $data = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : ['heroes' => [], 'next_id' => 1];
    if ($data === null) {
        throw new Exception('数据文件格式错误');
    }
    
    // 添加新英雄
    $newHero = [
        'id' => $data['next_id'],
        'name' => $input['name'],
        'image' => $input['image'],
        'description' => $input['description'],
        'sort' => count($data['heroes']) + 1  // 添加到最后
    ];
    
    $data['heroes'][] = $newHero;
    $data['next_id']++;
    
    // 使用临时文件写入
    $tempFile = $dataFile . '.tmp';
    if (file_put_contents($tempFile, json_encode($data, JSON_PRETTY_PRINT)) === false) {
        throw new Exception('写入临时文件失败');
    }
    if (!rename($tempFile, $dataFile)) {
        unlink($tempFile);
        throw new Exception('更新数据文件失败');
    }
    
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?> 